package br.com.comanda.webservice.business;

import java.util.List;

import br.com.comanda.webservice.dao.impl.ItemDAOImpl;
import br.com.comanda.webservice.model.Item;
import br.com.comanda.webservice.persistence.HibernateUtil;

public class ItemBusiness {

	public void save(Item item) {
		ItemDAOImpl dao = new ItemDAOImpl();
		dao.setSession(HibernateUtil.getSession());

		Item oldItem = dao.getItemByAccountAndProduct(
				item.getAccount().getId(), item.getProduct().getId());

		if (oldItem != null) {
			oldItem.setQuantity(oldItem.getQuantity() + item.getQuantity());
			oldItem.setTotal(oldItem.getTotal() + item.getTotal());
			item = oldItem;
		}

		dao.save(item);

	}

	public Item getItem(int accountId, int productId) {
		ItemDAOImpl dao = new ItemDAOImpl();
		dao.setSession(HibernateUtil.getSession());

		return dao.getItemByAccountAndProduct(accountId, productId);
	}

	public void remove(int id) {
		ItemDAOImpl dao = new ItemDAOImpl();
		dao.setSession(HibernateUtil.getSession());
		dao.delete(id);

	}

	public List<Item> findItensByAccount(int accountId) {
		ItemDAOImpl dao = new ItemDAOImpl();
		dao.setSession(HibernateUtil.getSession());

		return dao.findItensByAccount(accountId);
	}

	public void updateItem(Item item) {
		ItemDAOImpl dao = new ItemDAOImpl();
		dao.setSession(HibernateUtil.getSession());
		dao.updateQtdeItem(item);
	}
}
